package com.jeeplus.modules.monitor.utils;




import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileBean {
	private  static  String IAMGE="image/";



	/**
	 * 上次多个文件
	 * @param userUrlAr 多个文件的对象
	 * @return
	 * @throws Exception
	 */
	public static List<String> addPostsUrl(MultipartFile[] userUrlAr,String file)
			throws Exception {
		BufferedInputStream inputStream = null;
		List list = new ArrayList();

		FileOutputStream fop2 = null;
		for (int i = 0; i < userUrlAr.length; i++) {
			//判断是否为空文件
			if (!userUrlAr[i].isEmpty() && (userUrlAr[i].getSize() > 0L)) {
				//获取文件名字
				String fileString = getName(userUrlAr[i].getOriginalFilename().substring(
						userUrlAr[i].getOriginalFilename().lastIndexOf(".")));
				try {

					inputStream = new BufferedInputStream(
							userUrlAr[i].getInputStream());
					fop2 = new FileOutputStream(new File( file
							+ fileString));
					byte[] buffer = new byte[50];
					int is = 0;
					inputStream.mark(buffer.length);
					while (inputStream.read(buffer) != -1) {
						fop2.write(buffer);
						is++;
					}
					fop2.flush();
					list.add( fileString);
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					fileClose(inputStream);
					fileClose(fop2);
				}
			}
		}
		return list;
	}
	//重新生成文件名字
	private  static    String getName(String name){
		StringBuffer fileString = new StringBuffer();
		fileString.append(System.currentTimeMillis());
		fileString.append(Achieve.getUUIDString());
		fileString.append(name);
		return  fileString.toString();
	}
	/**
	 * 关闭IO流
	 * 
	 * @param inputStream
	 */
	private static void fileClose(BufferedInputStream inputStream) {
		try {
			if (inputStream != null)
				inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭IO流
	 * 
	 * @param fileOutputStream
	 */
	private static void fileClose(FileOutputStream fileOutputStream) {
		try {
			if (fileOutputStream != null)
				fileOutputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
